package com.yejiarong.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yejiarong.auth.bean.dto.UserSaveDto;
import com.yejiarong.auth.bean.entity.User;
import com.yejiarong.auth.mapper.IUserMapper;
import com.yejiarong.auth.service.IUserService;
import com.yejiarong.common.constant.CommonConstants;
import com.yejiarong.common.validate.ValidateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author YeJR
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    private final IUserMapper userMapper;

    private final PasswordEncoder passwordEncoder;

    public UserServiceImpl(IUserMapper userMapper, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 添加用户
     *
     * @param dto dto
     * @return 用户ID
     */
    @Override
    public Long addUser(UserSaveDto dto) {
        ValidateUtils.valid(dto);

        // 校验
        User repeatUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, dto.getUsername()).last(CommonConstants.LIMIT1));
        ValidateUtils.isNull(repeatUser, String.format("用户名%s已经存在", dto.getUsername()));

        // 保存
        User user = new User();
        user.setName(dto.getName());
        user.setUsername(dto.getUsername());
        user.setPassword(passwordEncoder.encode(dto.getPassword()));
        user.setStatus(1);
        user.setCreateTime(LocalDateTime.now());
        userMapper.insert(user);
        return user.getId();
    }
}
